package com.cc.sanjieduan.security.service;

import com.cc.sanjieduan.pojo.BaseUser;
import com.cc.sanjieduan.pojo.User;
import com.cc.sanjieduan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class MyUserDetailService implements UserDetailsService {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findUserByUserName(username);
        //返回值就是告诉spring security 我们数据库中的用户信息是什么
        if (user == null) {
            //用户不存在
            throw new UsernameNotFoundException("用户名不存在");
        }
        ArrayList<GrantedAuthority> list = new ArrayList<>();//用户的权限.我们先创建一个空的,因为这里还不确定密码对不对,所以不查询权限
        //我们把数据库中的密码设置到对象中,返回给springsecurity ,让它自己判断
     //   return new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        return new BaseUser(user.getUId(), username, user.getPassword(), list);
    }
}
